import time

from .dao import Dao
import re
from types import FunctionType

dao = None


def init_control(cf):
    global dao
    dao = Dao(cf['db'])


def dispatch(path, query_param):
    res = {'result': 'not found', 'code': 200}
    fun_name = re.search(r'/api/(.+)', path)
    if fun_name:
        try:
            fun = eval(fun_name.group(1))
            if isinstance(fun, FunctionType):
                res['result'] = fun(query_param)
                return res
        except Exception as error:
            print('dispatch->', error)
            res['result'] = str(error)

    res['code'] = 404
    return res


def html_param(params):
    sql = ['select * from HTML_PARAM where 1=1']
    query_param = []

    if 'createTime_start' in params:
        sql.append("and createTime>=strftime('%s',?,'utc')");
        query_param.append(params['createTime_start'][0])
    if 'createTime_end' in params:
        sql.append("and createTime<=strftime('%s',?,'utc')")
        query_param.append(params['createTime_end'][0])
    if 'pageNo' in params:
        offset = (int(params['pageNo'][0]) - 1) * int(params['pageSize'][0])
        sql.append('limit ? offset ?')
        query_param.append(int(params['pageSize'][0]))
        query_param.append(offset)
    sql_str = ' '.join(sql)
    print(sql_str, query_param)
    return dao.query(sql_str, query_param)


def sys_param(params):
    sql = ['select * from SYS_PARAM where 1=1']
    query_param = []

    if 'createTime' in params:
        sql.append("createTime<=strftime('%s',?,'utc')")
        query_param.append(params['createTime'][0])

    print(sql)
    return dao.query(' '.join(sql), query_param)


def clear_table(params={}):
    # 一个月前
    lastTime = time.time() + 100 if 'all' in params else time.time() - 3600 * 24 * 30
    sql_list = ['DELETE FROM HTML_PARAM WHERE createTime<%f' % lastTime,
                'DELETE FROM SYS_PARAM WHERE createTime<%f' % lastTime]
    print(sql_list)
    return dao.batch(sql_list)
